package com.example.learnvideo.ui

import android.content.Intent
import android.media.MediaMetadataRetriever
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.example.learnvideo.R
import com.example.learnvideo.base.BaseActivity
import com.example.learnvideo.databinding.ActivityVideoFrameBinding
import com.example.learnvideo.util.MediaUtil
import java.util.ArrayList

class VideoFrameActivity : BaseActivity<ActivityVideoFrameBinding>() {

    val URL_HTTPS = "http://82.157.163.217/海洋世界.mp4"
    private lateinit var mUri:Uri
    // 只在相册挑选视频的请求码
    private val chooseCode = 3

    override fun ActivityVideoFrameBinding.initBinding() {
        mUri = Uri.parse("android.resource://${packageName}/${R.raw.test}")
        //打开本地视频
        btnOpen.setOnClickListener {
//            // ACTION_GET_CONTENT只可选择近期的视频
//            val intent = Intent(Intent.ACTION_GET_CONTENT)
//            // ACTION_PICK可选择所有视频
//            //Intent intent = new Intent(Intent.ACTION_PICK);
//            // 类型为视频
//            intent.type = "video/*"
//            // 打开系统视频库
//            startActivityForResult(intent,chooseCode)
            mBinding.llCut.visibility = View.VISIBLE
            mBinding.vcPlay.prepare(mBinding.vvContent,mUri)
            mBinding.vcPlay.start()
        }

        //截一张图
        btnCutOne.setOnClickListener {
//            val bitmap = MediaUtil.getOneFrame(applicationContext,mUri,vvContent.currentPosition)
//            ivFrame.setImageBitmap(bitmap)
            val retriever = MediaMetadataRetriever()
            retriever.setDataSource(this@VideoFrameActivity,mUri)
            val bitmap = retriever.getFrameAtTime(vvContent.currentPosition.toLong())
            ivFrame.setImageBitmap(bitmap)
        }

        //截多张图
        btnCutMulti.setOnClickListener {
            val frameList = MediaUtil.getFrameList(this@VideoFrameActivity,mUri,vvContent.currentPosition,9)
            val intent = Intent(this@VideoFrameActivity,PhotoGridActivity::class.java)
            intent.putStringArrayListExtra("path_list",frameList as ArrayList<String>)
            startActivity(intent)
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == chooseCode){
            if (intent.data != null){
                mUri = intent.data!!
                mBinding.llCut.visibility = View.VISIBLE
                mBinding.vcPlay.prepare(mBinding.vvContent,mUri)
                mBinding.vcPlay.start()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        mBinding.vcPlay.resume()
    }

    override fun onPause() {
        super.onPause()
//        mBinding.vcPlay.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding.vcPlay.release()
    }
}